package net.suncaper.psychological.web.controller;

import net.suncaper.psychological.common.framework.simplemvc.RequestMapping;
import net.suncaper.psychological.common.utils.Result;
import net.suncaper.psychological.common.utils.MyDbUtil;
import net.suncaper.psychological.model.domain.Appointment;
import net.suncaper.psychological.service.IAppointmentService;
import net.suncaper.psychological.service.impl.AppointmentServiceImpl;
import com.alibaba.fastjson.JSON;
import net.suncaper.psychological.service.IUserService;
import net.suncaper.psychological.service.impl.UserServiceImpl;
import net.suncaper.psychological.model.vo.UserVO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RequestMapping("/api/appointment")
public class AppointmentController {
    private final IAppointmentService appointmentService = new AppointmentServiceImpl();
    private final IUserService userService = new UserServiceImpl();

    @RequestMapping("/add.do")
    public void addAppointment(HttpServletRequest request, HttpServletResponse response) {
        try {
            String jsonData = getRequestBody(request);
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);

            Appointment appointment = new Appointment();
            // 根据学号查找用户ID
            String studentIdStr = (String) data.get("studentId");
            if (studentIdStr == null || studentIdStr.trim().isEmpty()) {
                Result.error("学号不能为空").writeTo(response);
                return;
            }
            
            // 根据学号（username）查找用户ID
            String findUserSql = "SELECT id FROM user WHERE username = ?";
            List<Map<String, Object>> userResult = MyDbUtil.executeQueryMap(findUserSql, studentIdStr);
            if (userResult == null || userResult.isEmpty()) {
                Result.error("用户不存在，请检查学号是否正确").writeTo(response);
                return;
            }
            
            Long userId = ((Number) userResult.get(0).get("id")).longValue();
            appointment.setStudent_id(userId);
            System.out.println("学号: " + studentIdStr + " 对应的用户ID: " + userId);
            
            // 检查该学生是否已经有初访记录，防止重复申请
            String checkVisitSql = "SELECT vr.type, vr.conclusion FROM visit_record vr " +
                                 "JOIN appointment a ON vr.appointment_id = a.id " +
                                 "WHERE a.student_id = ? AND a.type = 'INITIAL' " +
                                 "ORDER BY vr.visit_time DESC LIMIT 1";
            List<Map<String, Object>> visitResult = MyDbUtil.executeQueryMap(checkVisitSql, userId);
            if (visitResult != null && !visitResult.isEmpty()) {
                Map<String, Object> visitInfo = visitResult.get(0);
                String visitType = (String) visitInfo.get("type");
                String conclusion = (String) visitInfo.get("conclusion");
                
                String errorMessage;
                if ("CONSULT".equals(visitType)) {
                    errorMessage = "您目前正在咨询阶段，不能重复申请初访预约。如需继续咨询请联系您的咨询师。";
                } else if ("COMPLETED".equals(visitType)) {
                    errorMessage = "您已经完成过初访，结论为：" + conclusion + "，不能重复申请初访预约。";
                } else {
                    errorMessage = "您已经完成过初访，不能重复申请初访预约。";
                }
                
                System.out.println("学号: " + studentIdStr + " 已有初访记录，类型: " + visitType + ", 结论: " + conclusion);
                Result.error(errorMessage).writeTo(response);
                return;
            }
            System.out.println("学号: " + studentIdStr + " 无初访记录，允许申请");
            
            appointment.setType("INITIAL");
            appointment.setStatus("PENDING");
            appointment.setApply_time((String) data.get("applyTime"));
            appointment.setScheduled_time((String) data.get("scheduledTime"));
            appointment.setScheduled_place((String) data.get("scheduledPlace"));

            // 处理紧急程度
            Object urgencyScoreObj = data.get("urgencyScore");
            Object isUrgentObj = data.get("isUrgent");
            if (urgencyScoreObj != null) {
                int urgencyScore = ((Number) urgencyScoreObj).intValue();
                appointment.setIs_urgent(urgencyScore >= 15);
                System.out.println("紧急程度分数: " + urgencyScore + ", 是否紧急: " + (urgencyScore >= 15));
            } else if (isUrgentObj != null) {
                appointment.setIs_urgent((Boolean) isUrgentObj);
            } else {
                appointment.setIs_urgent(false);
            }

            // duty_id: 随机生成1到9的数字
            Long dutyId = (long) (Math.random() * 9) + 1;
            appointment.setDuty_id(dutyId);

            boolean success = appointmentService.addAppointment(appointment);
            if (success) {
                String urgentMessage = appointment.getIs_urgent() ? "（紧急预约，将优先处理）" : "";
                Result.success(true, "预约成功" + urgentMessage).writeTo(response);
            } else {
                Result.error("预约失败").writeTo(response);
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细异常
            Result.error("预约异常: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/search.do")
    public void searchAppointment(HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println("开始查询预约，学号: " + request.getParameter("studentId"));
            
            String studentId = request.getParameter("studentId");
            if (studentId == null || studentId.trim().isEmpty()) {
                System.out.println("学号为空");
                Result.error("学号不能为空").writeTo(response);
                return;
            }

            System.out.println("调用service查询学号: " + studentId);
            Appointment appointment = appointmentService.getAppointmentByStudentId(studentId);
            
            if (appointment != null) {
                System.out.println("找到预约信息: " + appointment.getStudent_id());
                // 查找用户信息
                UserVO user = userService.getUserById(appointment.getStudent_id());
                java.util.HashMap<String, Object> result = new java.util.HashMap<>();
                result.put("appointment", appointment);
                result.put("user", user);
                Result.success(result, "查询成功").writeTo(response);
            } else {
                System.out.println("未找到预约信息");
                // 返回成功但数据为null，让前端处理
                Result.success(null, "未找到该学号的预约信息").writeTo(response);
            }
        } catch (Exception e) {
            System.out.println("查询预约异常: " + e.getMessage());
            e.printStackTrace();
            Result.error("查询异常: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/cancel.do")
    public void cancelAppointment(HttpServletRequest request, HttpServletResponse response) {
        try {
            String jsonData = getRequestBody(request);
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            Long appointmentId = Long.valueOf(data.get("appointmentId").toString());
            String cancelReason = (String) data.get("cancelReason");
            
            if (cancelReason == null || cancelReason.trim().isEmpty()) {
                Result.error("取消原因不能为空").writeTo(response);
                return;
            }
            
            boolean success = appointmentService.cancelAppointment(appointmentId, cancelReason);
            if (success) {
                Result.success(true, "预约取消成功").writeTo(response);
            } else {
                Result.error("预约取消失败").writeTo(response);
            }
        } catch (RuntimeException e) {
            if (e.getMessage().contains("24小时")) {
                Result.error(e.getMessage()).writeTo(response);
            } else {
                Result.error("预约取消失败: " + e.getMessage()).writeTo(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("取消预约异常: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/history.do")
    public void getHistoryAppointments(HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println("开始查询历史预约记录，学号: " + request.getParameter("studentId"));
            
            String studentId = request.getParameter("studentId");
            if (studentId == null || studentId.trim().isEmpty()) {
                System.out.println("学号为空");
                Result.error("学号不能为空").writeTo(response);
                return;
            }

            System.out.println("调用service查询历史记录，学号: " + studentId);
            List<Appointment> historyAppointments = appointmentService.getHistoryAppointmentsByStudentId(studentId);
            
            System.out.println("历史预约记录数量: " + historyAppointments.size());
            Result.success(historyAppointments, "查询历史记录成功").writeTo(response);
        } catch (Exception e) {
            System.out.println("查询历史预约异常: " + e.getMessage());
            e.printStackTrace();
            Result.error("查询历史记录异常: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/all.do")
    public void getAllAppointments(HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println("开始查询全部预约记录，学号: " + request.getParameter("studentId"));
            
            String studentId = request.getParameter("studentId");
            if (studentId == null || studentId.trim().isEmpty()) {
                System.out.println("学号为空");
                Result.error("学号不能为空").writeTo(response);
                return;
            }

            System.out.println("调用service查询全部记录，学号: " + studentId);
            List<Appointment> allAppointments = appointmentService.getAllAppointmentsByStudentId(studentId);
            
            System.out.println("全部预约记录数量: " + allAppointments.size());
            Result.success(allAppointments, "查询全部记录成功").writeTo(response);
        } catch (Exception e) {
            System.out.println("查询全部预约异常: " + e.getMessage());
            e.printStackTrace();
            Result.error("查询全部记录异常: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/update-arrangement")
    public void updateAppointmentArrangement(HttpServletRequest request, HttpServletResponse response) {
        try {
            String jsonData = getRequestBody(request);
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            Long appointmentId = Long.valueOf(data.get("id").toString());
            String scheduledTime = (String) data.get("scheduled_time");
            String scheduledPlace = (String) data.get("scheduled_place");
            Long consultantId = data.get("consultant_id") != null ? Long.valueOf(data.get("consultant_id").toString()) : null;
            
            // 获取原始预约信息
            String getAppointmentSql = "SELECT * FROM appointment WHERE id = ?";
            List<Map<String, Object>> appointmentResult = MyDbUtil.executeQueryMap(getAppointmentSql, appointmentId);
            
            if (appointmentResult.isEmpty()) {
                Result.error("未找到预约记录").writeTo(response);
                return;
            }
            
            Map<String, Object> originalAppointment = appointmentResult.get(0);
            String appointmentType = (String) originalAppointment.get("type");
            
            if ("INITIAL".equals(appointmentType)) {
                // 如果是初访预约，需要创建咨询预约
                Long studentId = ((Number) originalAppointment.get("student_id")).longValue();
                
                // 查找咨询师的值班安排
                String findDutySql = "SELECT id FROM duty_schedule WHERE user_id = ? AND role = 'CONSULTANT' " +
                                   "AND start_time <= ? AND end_time >= ? LIMIT 1";
                List<Map<String, Object>> dutyResult = MyDbUtil.executeQueryMap(findDutySql, consultantId, scheduledTime, scheduledTime);
                
                if (dutyResult.isEmpty()) {
                    Result.error("未找到咨询师的值班安排").writeTo(response);
                    return;
                }
                
                Long dutyId = ((Number) dutyResult.get(0).get("id")).longValue();
                
                // 创建咨询预约
                String createConsultSql = "INSERT INTO appointment(student_id, type, duty_id, status, apply_time, scheduled_time, scheduled_place) " +
                                        "VALUES (?, 'CONSULT', ?, 'APPROVED', NOW(), ?, ?)";
                
                int result = MyDbUtil.executeUpdate(createConsultSql, studentId, dutyId, scheduledTime, scheduledPlace);
                
                if (result > 0) {
                    Result.success(true, "咨询预约创建成功").writeTo(response);
                } else {
                    Result.error("咨询预约创建失败").writeTo(response);
                }
            } else {
                // 如果是咨询预约，直接更新
                boolean success = appointmentService.updateAppointmentArrangement(appointmentId, scheduledTime, scheduledPlace);
                
                if (success && consultantId != null) {
                    // 如果有指定咨询师，更新预约的duty_id
                    String findDutySql = "SELECT id FROM duty_schedule WHERE user_id = ? AND role = 'CONSULTANT' " +
                                       "AND start_time <= ? AND end_time >= ? LIMIT 1";
                    List<Map<String, Object>> dutyResult = MyDbUtil.executeQueryMap(findDutySql, consultantId, scheduledTime, scheduledTime);
                    
                    if (!dutyResult.isEmpty()) {
                        Long dutyId = ((Number) dutyResult.get(0).get("id")).longValue();
                        String updateDutySql = "UPDATE appointment SET duty_id = ? WHERE id = ?";
                        MyDbUtil.executeUpdate(updateDutySql, dutyId, appointmentId);
                    }
                }
                
                if (success) {
                    Result.success(true, "安排更新成功").writeTo(response);
                } else {
                    Result.error("安排更新失败").writeTo(response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("更新安排异常: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/update-status")
    public void updateAppointmentStatus(HttpServletRequest request, HttpServletResponse response) {
        try {
            String jsonData = getRequestBody(request);
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            Long appointmentId = Long.valueOf(data.get("id").toString());
            String status = (String) data.get("status");
            
            boolean success = appointmentService.updateAppointmentStatus(appointmentId, status);
            if (success) {
                Result.success(true, "状态更新成功").writeTo(response);
            } else {
                Result.error("状态更新失败").writeTo(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("更新状态异常: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/approved-initial")
    public void getApprovedInitialAppointments(HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println("开始查询已批准的初访预约");
            
            // 直接使用SQL查询，返回包含学号的数据
            String sql = "SELECT a.*, u.username as student_username, u.name as student_name, u.phone as student_phone " +
                        "FROM appointment a " +
                        "LEFT JOIN user u ON a.student_id = u.id " +
                        "WHERE a.type = 'INITIAL' AND a.status = 'APPROVED' " +
                        "ORDER BY a.scheduled_time ASC";
            
            System.out.println("执行查询SQL: " + sql);
            List<Map<String, Object>> appointments = MyDbUtil.executeQueryMap(sql);
            System.out.println("查询到已批准的初访预约数量: " + appointments.size());
            
            Result.success(appointments, "查询已批准的初访预约成功").writeTo(response);
        } catch (Exception e) {
            System.out.println("查询已批准的初访预约异常: " + e.getMessage());
            e.printStackTrace();
            Result.error("查询已批准的初访预约异常: " + e.getMessage()).writeTo(response);
        }
    }

    // 新增：管理员审核预约的接口
    @RequestMapping("/pending.do")
    public void getPendingAppointments(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取所有待审核的预约，按紧急程度和申请时间排序
            String sql = "SELECT a.*, u.name as student_name, u.phone as student_phone, u.gender as student_gender, u.extra_info as student_extra_info, u.username as student_username " +
                        "FROM appointment a " +
                        "LEFT JOIN user u ON a.student_id = u.id " +
                        "WHERE a.status = 'PENDING' " +
                        "ORDER BY a.is_urgent DESC, a.apply_time ASC";
            
            System.out.println("执行审核查询SQL: " + sql);
            List<Map<String, Object>> appointments = MyDbUtil.executeQueryMap(sql);
            System.out.println("查询到待审核预约数量: " + appointments.size());
            
            // 处理额外信息和调试输出
            for (Map<String, Object> appointment : appointments) {
                System.out.println("预约ID: " + appointment.get("id") + 
                                 ", student_id: " + appointment.get("student_id") + 
                                 ", student_name: " + appointment.get("student_name") +
                                 ", student_username: " + appointment.get("student_username"));
                
                String extraInfo = (String) appointment.get("student_extra_info");
                if (extraInfo != null && !extraInfo.trim().isEmpty()) {
                    try {
                        Map<String, Object> extraMap = JSON.parseObject(extraInfo, Map.class);
                        appointment.put("student_department", extraMap.get("department"));
                        appointment.put("student_class", extraMap.get("class"));
                    } catch (Exception e) {
                        System.out.println("解析额外信息失败: " + e.getMessage());
                    }
                }
            }
            
            Result.success(appointments, "查询待审核预约成功").writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("查询待审核预约失败: " + e.getMessage()).writeTo(response);
        }
    }

    // 新增：审核预约的接口
    @RequestMapping("/approve.do")
    public void approveAppointment(HttpServletRequest request, HttpServletResponse response) {
        try {
            String jsonData = getRequestBody(request);
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            Long appointmentId = Long.valueOf(data.get("appointmentId").toString());
            String action = (String) data.get("action"); // "approve" 或 "reject"
            Long reviewerId = Long.valueOf(data.get("reviewerId").toString());
            
            String newStatus = "approve".equals(action) ? "APPROVED" : "REJECTED";
            
            // 更新预约状态
            String sql = "UPDATE appointment SET status = ?, reviewer_id = ?, approve_time = NOW() WHERE id = ?";
            int result = MyDbUtil.executeUpdate(sql, newStatus, reviewerId, appointmentId);
            
            if (result > 0) {
                String message = "approve".equals(action) ? "预约已通过审核" : "预约已被拒绝";
                Result.success(true, message).writeTo(response);
            } else {
                Result.error("审核失败").writeTo(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("审核异常: " + e.getMessage()).writeTo(response);
        }
    }

    // 新增：优先排队的接口
    @RequestMapping("/priority.do")
    public void setPriorityAppointment(HttpServletRequest request, HttpServletResponse response) {
        try {
            String jsonData = getRequestBody(request);
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            Long appointmentId = Long.valueOf(data.get("appointmentId").toString());
            
            // 将预约设为紧急，并更新申请时间为当前时间（实现优先排队）
            String sql = "UPDATE appointment SET is_urgent = true, apply_time = NOW() WHERE id = ?";
            int result = MyDbUtil.executeUpdate(sql, appointmentId);
            
            if (result > 0) {
                Result.success(true, "已设置为优先排队").writeTo(response);
            } else {
                Result.error("设置优先排队失败").writeTo(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("设置优先排队异常: " + e.getMessage()).writeTo(response);
        }
    }

    private String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }
} 